package com.tomato.displaySample;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.renderer.XYMultipleSeriesRenderer;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.tomato.displaySample.widget.VerticalSeekBar;
import com.tomato.displaySample.widget.VerticalSeekBar.OnSeekBarChangeListener;

public class AD_display extends Activity implements OnClickListener, OnSeekBarChangeListener {

	Button ad_prevbutton,
		   ad_nextbutton,
		   ad_sequanceButton,
		   ad_controlSetButton,
		   ad_quitButton;
	Spinner ad_numberOfControllerSpiner;
	int currentPositionOfController;
	
	ImageView mGraphCh01, mGraphCh02, mGraphCh03, mGraphCh04, mLastSelectedView;
	TextView mChannelText01, mChannelText02, mChannelText03, mChannelText04, mLastSelectedChName;
	Button mCh01, mCh02, mCh03, mCh04, mCh05, mCh06, mCh07, mCh08;
	VerticalSeekBar mSeekBar01, mSeekBar02, mSeekBar03, mSeekBar04;
	GraphHelper mHelper;

	boolean mGraphActivated01, mGraphActivated02, mGraphActivated03, mGraphActivated04, mLastGraphActivated;
	boolean mGraphShowing01, mGraphShowing02, mGraphShowing03, mGraphShowing04, mLastGraphShowing;

	int mProgress;
	Button[] mButtons;
	float mChVoltageData[];
	String mChName[];
	HashMap<Button, Boolean> mShowingChStatus;
	HashMap<Button, ImageView> mShowingGraphStatus;
	HashMap<Button, TextView> mShowingChNameStatus;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.adview);
	    // TODO Auto-generated method stub
	    Intent intent = getIntent();
	    int position = intent.getIntExtra("controllerNum2", 0);
		ArrayAdapter<String> controller = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
		controller.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		controller.add(getString(R.string.controller_select));
		controller.add(getString(R.string.controller_test_data01));
		controller.add(getString(R.string.controller_test_data02));
		controller.add(getString(R.string.controller_test_data03));
		controller.add(getString(R.string.controller_test_data04));
		controller.add(getString(R.string.controller_test_data05));
		controller.add(getString(R.string.controller_test_data06));
		controller.add(getString(R.string.controller_test_data07));
		
	    ad_prevbutton = (Button)findViewById(R.id.ad_prevbutton);
	    ad_nextbutton = (Button)findViewById(R.id.ad_nextbutton);
	    ad_sequanceButton = (Button)findViewById(R.id.ad_sequanceButton);
	    ad_controlSetButton = (Button)findViewById(R.id.ad_controlSetButton);
	    ad_quitButton = (Button)findViewById(R.id.ad_quitButton);

	    ad_numberOfControllerSpiner = (Spinner)findViewById(R.id.ad_numberOfControllerSpiner);
	    ad_numberOfControllerSpiner.setAdapter(controller);
	    ad_numberOfControllerSpiner.setSelection(position, false);
	    
	    ad_prevbutton.setOnClickListener(button_Listener);
	    ad_nextbutton.setOnClickListener(button_Listener);
	    ad_sequanceButton.setOnClickListener(button_Listener);
	    ad_controlSetButton.setOnClickListener(button_Listener);
	    ad_quitButton.setOnClickListener(button_Listener);
	    
	    ad_numberOfControllerSpiner.setOnItemSelectedListener(spiner_Listener);
	    
	    mHelper = new GraphHelper();
	    
	    mSeekBar01 = (VerticalSeekBar) findViewById(R.id.vertical_seekbar01);
	    mSeekBar02 = (VerticalSeekBar) findViewById(R.id.vertical_seekbar02);
	    mSeekBar03 = (VerticalSeekBar) findViewById(R.id.vertical_seekbar03);
	    mSeekBar04 = (VerticalSeekBar) findViewById(R.id.vertical_seekbar04);
	    
	    mSeekBar01.setMax(100);
	    mSeekBar01.setProgress(65);
	    mSeekBar01.setOnSeekBarChangeListener(this);
	    mSeekBar02.setMax(100);
	    mSeekBar02.setProgress(65);
	    mSeekBar02.setOnSeekBarChangeListener(this);
	    mSeekBar03.setMax(100);
	    mSeekBar03.setProgress(65);
	    mSeekBar03.setOnSeekBarChangeListener(this);
	    mSeekBar04.setMax(100);
	    mSeekBar04.setProgress(65);
	    mSeekBar04.setOnSeekBarChangeListener(this);
	    
	    mChannelText01 = (TextView) findViewById(R.id.channel_name01);
	    mChannelText02 = (TextView) findViewById(R.id.channel_name02);
	    mChannelText03 = (TextView) findViewById(R.id.channel_name03);
	    mChannelText04 = (TextView) findViewById(R.id.channel_name04);
	    	    
	    mGraphCh01 = (ImageView) findViewById(R.id.graph_view01);
	    mGraphCh01.setOnClickListener(this);
	    mGraphCh02 = (ImageView) findViewById(R.id.graph_view02);
	    mGraphCh02.setOnClickListener(this);
	    mGraphCh03 = (ImageView) findViewById(R.id.graph_view03);
	    mGraphCh03.setOnClickListener(this);
	    mGraphCh04 = (ImageView) findViewById(R.id.graph_view04);
	    mGraphCh04.setOnClickListener(this);
	    
	    mCh01 = (Button) findViewById(R.id.ad_middleDataCh1);
	    mCh02 = (Button) findViewById(R.id.ad_middleDataCh2);
	    mCh03 = (Button) findViewById(R.id.ad_middleDataCh3);
	    mCh04 = (Button) findViewById(R.id.ad_middleDataCh4);
	    mCh05 = (Button) findViewById(R.id.ad_middleDataCh5);
	    mCh06 = (Button) findViewById(R.id.ad_middleDataCh6);
	    mCh07 = (Button) findViewById(R.id.ad_middleDataCh7);
	    mCh08 = (Button) findViewById(R.id.ad_middleDataCh8);

	    mChName = getResources().getStringArray(R.array.channel_names);
	    mButtons = new Button[]{mCh01, mCh02, mCh03, mCh04, mCh05, mCh06, mCh07, mCh08};
	    mShowingChStatus = new HashMap<Button, Boolean>();
	    mShowingGraphStatus = new HashMap<Button, ImageView>();
	    mShowingChNameStatus = new HashMap<Button, TextView>();
	    
	    // this is testData
	    mChVoltageData = new float[] {5.1f, -3.3f, 1.0f, -999999999, -999999999, -999999999, -999999999, -999999999, -999999999};
	    	    
	    for (int i = 0; i < mButtons.length; i++) {
	    	mButtons[i].setText(mChVoltageData[i] == -999999999 ? getString(R.string.not_available_channel) : 
	    					mChVoltageData[i] > 0 ? "+" + Float.toString(mChVoltageData[i]) : Float.toString(mChVoltageData[i]));
	    	mButtons[i].setOnClickListener(this);
	    	mShowingChStatus.put(mButtons[i], false);
	    }  
	}	
	
	// test data ... sin graph
	private void setChannelGraph(int frequent) {
		String[] titles = new String[] {""};
		List<double[]> x = new ArrayList<double[]>();
		List<double[]> values = new ArrayList<double[]>();
		int step = frequent;
		int count = 360 / step + 1;
		x.add(new double[count]);
		x.add(new double[count]);
		double[] sinValues = new double[count];
		double[] cosValues = new double[count];
		values.add(sinValues);
		values.add(cosValues);
		for (int i = 0; i < count; i++) {
			int angle = i * step;
			x.get(0)[i] = angle;
			x.get(1)[i] = angle;
			double rAngle = Math.toRadians(angle);
			sinValues[i] = Math.sin(rAngle);
			cosValues[i] = Math.cos(rAngle);
		}
		int[] colors = new int[] { Color.WHITE };
		PointStyle[] styles = new PointStyle[] {PointStyle.CIRCLE};
		XYMultipleSeriesRenderer renderer = mHelper.buildRenderer(colors, styles);
		mHelper.setChartSettings(renderer, "", "", "", 0, 360, -1, 1, Color.BLACK, Color.BLACK);
		renderer.setShowLegend(false);
		renderer.setShowAxes(false);
		renderer.setZoomButtonsVisible(false);
		renderer.setBackgroundColor(Color.BLACK);
        renderer.setApplyBackgroundColor(true); 
		
		GraphicalView view = ChartFactory.getLineChartView(
								this, mHelper.buildDataset(titles, x, values), renderer);
		view.setDrawingCacheEnabled(true);
		view.layout(0, 0, 1200, 800);
		view.setBackgroundColor(Color.WHITE);
		view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
		view.buildDrawingCache(true);
		Bitmap graph = Bitmap.createScaledBitmap(view.getDrawingCache(), 190, 160, false);
		mLastSelectedView.setImageBitmap(graph);
	}
	
	private OnClickListener button_Listener=new OnClickListener() {
		//@Override
		public void onClick(View v) {
			switch(v.getId()){
			case R.id.ad_prevbutton:
				{
					finish();
					break;
				}
			case R.id.ad_nextbutton:
				{
					Intent intent=new Intent(AD_display.this, Camera_display.class);
					intent.putExtra("controllerNum3", currentPositionOfController);
					startActivity(intent);
					break;
				}
			case R.id.ad_sequanceButton:
			{	
				Intent intent=new Intent(AD_display.this, sequance_display.class);
				startActivity(intent);
				break;
			}
			case R.id.ad_controlSetButton:		{
				Intent intent=new Intent(AD_display.this, Control_display.class);
				startActivity(intent);
				break;
			}
			case R.id.ad_quitButton:		{
				break;
			}
			}
		}
	};
	
	private OnItemSelectedListener spiner_Listener = new OnItemSelectedListener() {

		//@Override
		public void onItemSelected(AdapterView<?> parent,View view, int position, long id) {
			// TODO Auto-generated method stub
			currentPositionOfController = position;
			PopupMenu popupMenu = new PopupMenu(AD_display.this, view);
			 popupMenu.getMenuInflater().inflate(R.menu.motor_popup,popupMenu.getMenu());
			 popupMenu.show();
		    // ポップアップメニューのメニュー項目のクリック処理
			 popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
				 //@Override
				 public boolean onMenuItemClick(MenuItem item) {
		            // 押されたメニュー項目名をToastで表示
		            Toast.makeText(AD_display.this, item.getTitle(),  Toast.LENGTH_SHORT).show();
		            return true;
		        }
			 });
		}

		//@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
			
		}
		
		
	};

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
			case R.id.graph_view01:
				toggleGraphViewStatus(mGraphShowing01, mGraphActivated01, mGraphCh01, mChannelText01);
				break;
			case R.id.graph_view02:
				toggleGraphViewStatus(mGraphShowing02, mGraphActivated02, mGraphCh02, mChannelText02);
				break;
			case R.id.graph_view03:
				toggleGraphViewStatus(mGraphShowing03, mGraphActivated03, mGraphCh03, mChannelText03);
				break;
			case R.id.graph_view04:
				toggleGraphViewStatus(mGraphShowing04, mGraphActivated04, mGraphCh04, mChannelText04);
				break;
			case R.id.ad_middleDataCh1:
				selectShowGraph(mButtons[0]);
				break;
			case R.id.ad_middleDataCh2:
				selectShowGraph(mButtons[1]);
				break;
			case R.id.ad_middleDataCh3:
				selectShowGraph(mButtons[2]);
				break;
			case R.id.ad_middleDataCh4:
				selectShowGraph(mButtons[3]);
				break;
			case R.id.ad_middleDataCh5:
				selectShowGraph(mButtons[4]);
				break;
			case R.id.ad_middleDataCh6:
				selectShowGraph(mButtons[5]);
				break;
			case R.id.ad_middleDataCh7:
				selectShowGraph(mButtons[6]);
				break;
			case R.id.ad_middleDataCh8:
				selectShowGraph(mButtons[7]);
				break;
				
		}
	}
	
	private void toggleGraphViewStatus(boolean graphShowing, boolean activeState, ImageView lastSelectedView, TextView lastSelectedChName) {
		if (!graphShowing) activeState = true;
		else activeState = false;
		mLastGraphShowing = graphShowing;
		mLastGraphActivated = activeState;
		mLastSelectedView = lastSelectedView;
		mLastSelectedChName = lastSelectedChName;
	}
	
	// current method used test data. 
	private void selectShowGraph(Button selectedButton) {
		if (mShowingChStatus.get(selectedButton)) {
			mShowingChStatus.put(selectedButton, false);
			mShowingChNameStatus.get(selectedButton).setText(getString(R.string.channel));
			mShowingGraphStatus.get(selectedButton).setImageBitmap(null);
			
			selectedButton.setBackgroundColor(R.color.dio_notSelected);
			mLastGraphShowing = false;
			mLastGraphActivated = false;
			mLastSelectedView = null;
		} else {
			if (!selectedButton.getText().equals(getString(R.string.not_available_channel)) 
					&& !mLastGraphShowing && mLastGraphActivated && mLastSelectedView != null) {
				
				for (int i = 0; i < mButtons.length; i++) {
					if (mButtons[i] == selectedButton) {
						mLastSelectedChName.setText(mChName[i]);
						break;
					}
				}
				
				setChannelGraph(4);
				
				selectedButton.setBackgroundColor(getResources().getColor(R.color.dio_On));
				mShowingChStatus.put(selectedButton, true);
				mShowingGraphStatus.put(selectedButton, mLastSelectedView);
				mShowingChNameStatus.put(selectedButton, mLastSelectedChName);
				mLastGraphShowing = true;
			} else {
				mLastGraphActivated = false;
			}
		}
	}

	@Override
	public void onProgressChanged(VerticalSeekBar seekBar, int progress, boolean fromUser) {	
		mProgress = progress;
	}
	
	@Override
	public void onStartTrackingTouch(VerticalSeekBar seekBar) {		
	}

	@Override
	public void onStopTrackingTouch(VerticalSeekBar seekBar) {
		int frequentData = 0;
		if (seekBar == mSeekBar01 && mGraphShowing01) {
			mLastSelectedView = mGraphCh01;
		} else if (seekBar == mSeekBar02 && mGraphShowing02) {
			mLastSelectedView = mGraphCh02;
		}  else if (seekBar == mSeekBar03 && mGraphShowing03) {
			mLastSelectedView = mGraphCh03;
		}  else if (seekBar == mSeekBar04 && mGraphShowing04) {
			mLastSelectedView = mGraphCh04;
		}		
		
		if (mProgress <= 100 && mProgress > 81) {
			seekBar.setProgress(96);
			frequentData = 1;
		} else if (mProgress <= 80 && mProgress > 50) {
			seekBar.setProgress(65);
			frequentData = 2;
		} else if (mProgress <= 49 && mProgress > 18) {
			seekBar.setProgress(36);
			frequentData = 3;
		} else {
			seekBar.setProgress(5);
			frequentData = 4;
		}
		
		if (mLastSelectedView != null) {
			setChannelGraph(frequentData);
		}		
	}
}
